<?php
/**
 * Created by PhpStorm.
 * User: yandian
 * Date: 2017/4/21
 * Time: 20:54
 */

namespace app\weixin\controller;


use app\common\controller\LiteBase;
use app\common\model\ActivityHire;
use app\common\util\Assert;
use app\common\util\DateTimeUtil;
use app\common\util\LoginManager;

class Activity extends LiteBase
{
    private function getData()
    {
        return \app\common\model\Activity::instance()
            ->gotoPage()
            ->order('sort desc,id desc')->select();
    }

    public function index()
    {
        $this->assign('m', $this->getData());
        return $this->fetch();
    }

    public function jsonList()
    {
        return $this->jsonSuccess($this->getData());
    }

    public function detail()
    {
        $id = I('get.id', 0, 'intval');
        if ($id) {
            $m = \app\common\model\Activity::instance()->where(['id' => $id])->find();
            if (!empty($m)) {
                $this->assign('m', $m);
                return $this->fetch();
            }
        }
        return '活动已下架';
    }

    public function apply()
    {
        LoginManager::doCheckLogin();
        $id = I('get.id', 0, 'intval');
        if ($id) {
            $m = \app\common\model\Activity::instance()->where(['id' => $id])->count();
            if (!empty($m)) {
                return $this->fetch();
            }
        }
        return '活动已下架';
    }

    public function hire()
    {
        if (IS_POST) {
            try {
                $saveData = Assert::notEmpty(I('post.'), ['username', 'telephone', 'workplace', 'activity_id']);
                $member_id = LoginManager::getLoginUserId();
                $activity_id = intval($saveData['activity_id']);
                if (ActivityHire::instance()->where(['activity_id' => $activity_id, 'member_id' => $member_id])->count()) {
                    return $this->jsonFail('您已经报名了，谢谢!');
                }
                $activityRow = \app\common\model\Activity::instance()->where(['id' => $activity_id])->find();
                if ($activityRow['man_num'] < ActivityHire::instance()->where(['activity_id' => $activity_id])->count() + 1) {
                    return $this->jsonFail('活动报名人数已满，无法继续报名');
                }
                $saveData['create_time'] = DateTimeUtil::now();
                $saveData['member_id'] = $member_id;
                ActivityHire::instance()->add($saveData);
                return $this->jsonSuccess();
            } catch (\Exception $ex) {
                return $this->jsonFail($ex->getMessage());
            }
        }
    }
}